package xing.appwidget.utils

import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import android.content.pm.ApplicationInfo
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.content.res.ColorStateList
import android.graphics.drawable.Drawable
import androidx.core.graphics.drawable.DrawableCompat
import xing.appwidget.bean.ApplicationItem

object Utils {
    fun isSystemApp(pInfo: PackageInfo): Boolean { //判断是否是系统软件（系统软件更新后也成为了User）
        return pInfo.applicationInfo.flags and (ApplicationInfo.FLAG_SYSTEM or ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0
    }

    fun scanForActivity(context: Context?): Activity? {
        return if (context == null) {
            null
        } else if (context is Activity) {
            context
        } else {
            if (context is ContextWrapper) scanForActivity(context.baseContext) else null
        }
    }

    fun tryConvertToActivity(context: Context): Context {
        return (scanForActivity(context) ?: context)
    }

    fun tintDrawable(drawable: Drawable?, colorInt: Int): Drawable? {
        val wrappedDrawable = DrawableCompat.wrap(drawable!!)
        DrawableCompat.setTintList(wrappedDrawable, ColorStateList.valueOf(colorInt))
        return wrappedDrawable
    }

    fun toApplicationItem(pm: PackageManager, packageInfo: PackageInfo): ApplicationItem {
        val applicationInfo = packageInfo.applicationInfo
        val appName = pm.getApplicationLabel(applicationInfo).toString()
        val packageName = packageInfo.packageName
        val appIcon = pm.getApplicationIcon(applicationInfo)
        return ApplicationItem(appName, packageName,
                appIcon, applicationInfo.enabled,
                applicationInfo.loadLabel(pm).toString(),
                packageInfo.versionName,
                applicationInfo.targetSdkVersion,
                applicationInfo.uid)
//        item.flags = applicationInfo.flags
//        item.uid = applicationInfo.uid
//        item.debuggable = applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE != 0
//        item.isUser = applicationInfo.flags and ApplicationInfo.FLAG_SYSTEM == 0
//        item.isDisabled = !applicationInfo.enabled
//        item.label = applicationInfo.loadLabel(pm!!).toString()
//        item.sdk = applicationInfo.targetSdkVersion
//        item.versionName = packageInfo.versionName
//        item.versionCode = getVersionCode(packageInfo)
//        item.sharedUserId = packageInfo.sharedUserId
//        item.sha = Utils.getIssuerAndAlg(packageInfo)
//        item.firstInstallTime = packageInfo.firstInstallTime
//        item.lastUpdateTime = packageInfo.lastUpdateTime
//        item.hasActivities = packageInfo.activities != null
//        item.blockedCount = 0
    }
}